<?php

namespace App\Admin\Actions\Ddb;

use App\Actions\DdbHookAction;
use App\Logics\AdminOperationLogLogic;
use App\Models\AdminUser;
use App\Policies\Admin\DdbPolicy;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Delete extends RowAction
{
    /**
     * @return string
     */
	protected $title = '<i class="feather icon-trash">删除</i>';
    protected $model;
    protected $row;

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $is_super_manger = $admin_user->isSuperManger();
        $table = $request->table;
        $modelClass = $request->modelClass;
        $id = $this->getKey();

        if (in_array($table, ['ddb_first', 'ddb_second'])) {
            $current_time = $table == 'ddb_first' ? 1 : 2;
        } else {
            $current_time = $table;
        }
        $relation_row = $modelClass::query()->where('id', $id)->first();
        if (!DdbPolicy::make($relation_row, $admin_user, $current_time)->can_delete()) {
            return $this->response()->error('无权删除' . $request->desc);
        }

        if ($is_super_manger) {
            DB::table($table)->where('name', $relation_row->name)->where('csrq', $relation_row->csrq)->delete();
        } else {
            # 删除
            DB::table($table)->where('id', $id)->delete();
        }
        # 更新主要信息
        DdbHookAction::make(null, $admin_user)->updateDdbMainRow($relation_row, $table);
        
        # 日志
        try {
            $title = $modelClass::NAME;
            $desc = '';
            $desc .= isset($relation_row->name) ? "姓名：{$relation_row->name}，出生日期：{$relation_row->csrq}" : "";
            AdminOperationLogLogic::make(null, $admin_user)->delete(["删除{$title}{$desc}"])->log();
        } catch (\Throwable $th) {
        }
        return $this->response()->success('删除成功' . $request->desc)->refresh();
    }

    /**
	 * @return string|array|void
	 */
	public function confirm()
	{
        $text = '';
        $row = $this->getRow();
        if ($row) {
            $text = "确定删除{$row->name}？";
        }
        return ['确认删除', $text];
	}

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    public function parameters()
    {
        $row = $this->getRow();
        return [
            'table'  => $row->getTable(),
            'desc' => "姓名 {$row->name}",
            'modelClass' => get_class($row)
        ];
    }
}
